package com.heima.account.handler;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.heima.account.service.AccountAPIService;
import com.heima.commons.enums.BusinessErrors;
import com.heima.commons.exception.BusinessRuntimeException;
import com.heima.commons.utils.CommonsUtils;
import com.heima.modules.po.AccountPO;
import com.heima.modules.po.VehiclePO;
import okhttp3.*;
import org.apache.commons.codec.binary.StringUtils;
import org.apache.commons.io.FileUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import org.apache.commons.codec.binary.Base64;

@Component
public class AiHelper {
    @Value("${baidu.apikey}")
    private String API_KEY;
    @Value("${baidu.secretkey}")
    private String SECRET_KEY;


    private final static Logger logger = LoggerFactory.getLogger(AiHelper.class);
    final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();









    public static void main(String []args) throws IOException {

        VehiclePO vehiclePO = new VehiclePO();
        vehiclePO.setCarFrontPhoto("http://192.168.64.100:9005/hitch/1721213271605-carfront.jpg");
        vehiclePO.setCarBackPhoto("http://192.168.64.100:9005/hitch/1721214292890-Snipaste_2024-07-17_19-04-22.png");
        String code = new AiHelper().getLicense(vehiclePO);
        System.out.println(code);
    }



    /*

    图像识别，获取车牌信息
    文档（行驶证识别）：https://cloud.baidu.com/doc/OCR/s/yk3h7y3ks
    文档（车牌识别）：https://cloud.baidu.com/doc/OCR/s/ck3h7y191
    获取车辆照片url
    将url下载到某个临时文件夹
    将文件编码为base64
    调百度AI接口，返回对应信息
    对比：行驶证车牌 和 车辆车牌是否一致
    如果一致，设置车牌信息，认证通过，身份变更为车主

    简化版业务流程（至少完成）：识别车辆车牌号即可

    * */
    public String getLicense(VehiclePO vehiclePO) throws IOException {

        // 获取车辆照片url
        String carFrontPhoto = vehiclePO.getCarFrontPhoto();
        String carBackPhoto = vehiclePO.getCarBackPhoto();

        //         将url下载到某个临时文件夹



        String filePath = "J:\\ProjectFile\\hitch\\hitch\\backend\\hitch-account\\src\\main\\resources\\temp\\carFront\\carFront.jpg";
        String filePath2 = "J:\\ProjectFile\\hitch\\hitch\\backend\\hitch-account\\src\\main\\resources\\temp\\carBack\\carBack.png";


        URL carFrontUrl = new URL(carFrontPhoto);
        HttpURLConnection conn = (HttpURLConnection) carFrontUrl.openConnection();
        conn.setRequestMethod("GET");
        InputStream inputStream = conn.getInputStream();
        FileOutputStream outputStream = new FileOutputStream(filePath);
        byte[] buffer = new byte[1024];
        int bytesRead;
        while ((bytesRead = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, bytesRead);
        }


        URL carBackUrl = new URL(carBackPhoto);
        HttpURLConnection conn2 = (HttpURLConnection) carBackUrl.openConnection();
        conn2.setRequestMethod("GET");
        InputStream inputStream2 = conn2.getInputStream();
        FileOutputStream outputStream2 = new FileOutputStream(filePath2);
        byte[] buffer2 = new byte[1024];
        int bytesRead2;
        while ((bytesRead2 = inputStream2.read(buffer2)) != -1) {
            outputStream2.write(buffer2, 0, bytesRead2);
        }


        // 将文件编码为base64
        byte[] fileContent = Files.readAllBytes(Path.of(filePath));
        String base64carFront = Base64.encodeBase64String(fileContent);
        System.out.println(base64carFront);
        String encodedBase64 = URLEncoder.encode(base64carFront, StandardCharsets.UTF_8);
        System.out.println(encodedBase64);


        byte[] fileContent2 = Files.readAllBytes(Path.of(filePath2));
        String base64carBack = Base64.encodeBase64String(fileContent2);
        System.out.println(base64carBack);
        String encodedBase65 = URLEncoder.encode(base64carBack, StandardCharsets.UTF_8);


        // 调百度AI接口，返回对应信息
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "image=" + encodedBase64 + "&multi_detect=true&multi_scale=true&detect_complete=false&detect_risk=false");
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/rest/2.0/ocr/v1/license_plate?access_token=" + "24.247dce2baf2c1ea33937a5469f9e37d9.2592000.1723790492.282335-95454478")
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .addHeader("Accept", "application/json")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        String responseBody = response.body().string();
        System.out.println(responseBody);


// 使用 Gson 解析 JSON
        Gson gson = new Gson();
        JsonObject jsonObject = gson.fromJson(responseBody, JsonObject.class);
// 提取 number 字段的值
        JsonArray wordsResult = jsonObject.getAsJsonArray("words_result");


        JsonObject firstResult = wordsResult.get(0).getAsJsonObject();
        String numberValue = firstResult.get("number").getAsString();
        // 打印出 number 的值
        System.out.println("Number: " + numberValue);


        MediaType mediaType2 = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body2 = RequestBody.create(mediaType2, "image=" + encodedBase65 + "&detect_direction=false&unified=false&quality_warn=false&risk_warn=false");
        Request request2 = new Request.Builder()
                .url("https://aip.baidubce.com/rest/2.0/ocr/v1/vehicle_license?access_token=" + "24.247dce2baf2c1ea33937a5469f9e37d9.2592000.1723790492.282335-95454478")
                .method("POST", body2)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .addHeader("Accept", "application/json")
                .build();
        Response response2 = HTTP_CLIENT.newCall(request2).execute();
        String responseBody2 = response2.body().string();
        System.out.println(responseBody2);

        JsonObject jsonObject2 = gson.fromJson(responseBody2, JsonObject.class);
        // 获取 "words_result" 对象
        JsonObject wordsResult2 = jsonObject2.getAsJsonObject("words_result");
        String licensePlateNumber = wordsResult2.getAsJsonObject("号牌号码").get("words").getAsString();
        System.out.println(licensePlateNumber);
        logger.info(licensePlateNumber);
        logger.info(numberValue);
        // 对比：行驶证车牌 和 车辆车牌是否一致
        if (StringUtils.equals(licensePlateNumber,numberValue)) {
            return licensePlateNumber;
        } else {
            // 如果一致，设置车牌信息，认证通过，身份变更为车主
            throw new BusinessRuntimeException(BusinessErrors.DATA_NOT_EXIST, "车辆认证信息不一致");
        }


    }








}
